using Service.Framework;
using System.Reflection;
using Db;
using Service.Framework.Register;
using Microsoft.OpenApi.Models;
using IdentityServer4.AccessTokenValidation;
using Exceptionless;
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseAgileConfig();
// Add services to the container.
builder.Services.AddExceptionless(builder.Configuration);
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Product.Api API", Version = "v1", Description = "# Product.Api service api..." });
    // Set the comments path for the Swagger JSON and UI.
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
    {
        Description = "在下框中输入请求头中需要添加Jwt授权Token：Bearer Token",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme{
                    Reference = new OpenApiReference {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"}
                },new string[] { }
            }
        });
});
builder.Services.Configure<ConsulRegisterOptions>(builder.Configuration.GetSection("ConsulSetting"));
builder.Services.AddConsulRegister();
builder.Services.AddSqlSugarConnection(builder.Configuration);

builder.Services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
       .AddIdentityServerAuthentication("productService", options =>
       {
           options.Authority = builder.Configuration.GetValue<string>("Authority");// "https://docker.for.win.localhost:7128";// "https://docker.for.win.localhost:7128"; //"http://docker.for.win.localhost:5065";//鉴权中心地址
           options.ApiName = "productApi";
           options.SupportedTokens = SupportedTokens.Both;
           options.ApiSecret = "productApisecret";
           options.RequireHttpsMetadata = false;

           // options.SaveToken = true;
       });

builder.Services.AddCap(x =>
{
    //  x.UseSqlServer("Data Source=111.230.108.248;Initial Catalog=Product;Pooling=True;User Id=sa;Password=A#07545742845wa;connect Timeout=30;Encrypt=True;TrustServerCertificate=True;");
    x.UseSqlServer("Data Source=101.126.19.134;Initial Catalog=Product;Pooling=True;User Id=sa;Password=liujian1368928.;connect Timeout=30;Encrypt=True;TrustServerCertificate=True;");
    // x.UseRabbitMQ("rabbitmq");
    // x.UseRabbitMQ("rabbitmq");
    x.UseRabbitMQ(rb =>
    {
        rb.HostName = builder.Configuration.GetValue<string>("RabbitMQ:HostName");
        rb.Port = builder.Configuration.GetValue<int>("RabbitMQ:Port");
        rb.VirtualHost = builder.Configuration.GetValue<string>("RabbitMQ:VirtualHost");
        rb.UserName = builder.Configuration.GetValue<string>("RabbitMQ:UserName");
        rb.Password = builder.Configuration.GetValue<string>("RabbitMQ:Password");
        rb.ExchangeName = builder.Configuration.GetValue<string>("RabbitMQ:ExchangeName");
    });
});
var authenticationProviderKey = "ProductService";
builder.Services.AddAuthentication(authenticationProviderKey)
              .AddJwtBearer(authenticationProviderKey, options =>
              {
                  options.Authority = "https://www.liujian520.asia:5001";//id4服务地址
                  options.Audience = "productApi";//id4 api资源里的apiname
                  options.RequireHttpsMetadata = false; //不使用https
                  options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
              });

builder.Services.AddAuthorization();
var app = builder.Build();
var hosrServer = app.Services.GetRequiredService<IHostApplicationLifetime>();
await app.Services.GetService<IConsulRegister>()!.ConsulRegistAsync();


app.UseHealthCheckMiddleware();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{

}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Product.Api API V1");
});
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

app.UseExceptionless();

app.MapGet("/test", (IConfiguration configuration) =>
{
    Console.WriteLine("执行开始" + DateTime.Now.ToString());

    //Thread.Sleep(6000);


    return $"{Assembly.GetExecutingAssembly().FullName};当前时间：{DateTime.Now:G};Port：{configuration["ConsulSetting:Port"]}";
});
app.MapControllers();
app.Run();
